package com.second.app.thread.stack;

import java.util.ArrayList;
import java.util.List;

/**
 * @author gyz
 * @date 2021/1/26 16:14
 * <p>
 * 一个生产，一个消费，操作栈
 * notifyAll()解决线程假死的问题
 */
public class MyStack {

    private final List<String> list = new ArrayList<>();

    /**
     * 往list中添加元素
     */
    synchronized public void push() {
        try {
            if (list.size() == 1) {
                this.wait();
            }
            list.add("anything=" + Math.random());
            this.notify();
            System.out.println(Thread.currentThread().getName() + ":push=" + list.size());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * list中取元素
     */
    synchronized public void pop() {
        try {
            if (list.size() == 0) {
                System.out.println(Thread.currentThread().getName() + "线程呈wait状态");
                this.wait();
            }
            String value = "" + list.get(0);
            list.remove(0);
            this.notify();
            System.out.println(Thread.currentThread().getName() + ":pop=" + list.size());
            System.out.println(Thread.currentThread().getName() + ":pop出的值=" + value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
